import pytest
from data.models import Parking
from data.parkings import create_parking_json, get_parking_json, update_parking_json
from errors import Missing
from sqlalchemy import func


@pytest.fixture
def parking_json():
    return {
        "address": "Moskovskiy pr., 131",
        "opened": True,
        "count_places": 300,
        "count_available_places": 300,
    }


def test_create_parking_json(db, parking_json):
    result = create_parking_json(
        address=parking_json["address"],
        opened=parking_json["opened"],
        count_places=parking_json["count_places"],
        count_available_places=parking_json["count_available_places"],
    )
    assert result["id"] is not None
    assert result == {"id": result["id"], **parking_json}
    assert db.session.query(func.count(Parking.id)).scalar() == 1


def test_get_parking(parking_json):
    result = get_parking_json(parking_id=1)
    assert result == {"id": result["id"], **parking_json}


def test_get_parking_with_wrong_id():
    with pytest.raises(Missing):
        get_parking_json(parking_id=123)


def test_update_parking(db):
    updated = {
        "address": "Updated Address",
        "opened": False,
        "count_places": 123,
        "count_available_places": 456,
    }

    result = update_parking_json(parking_id=1, **updated)
    assert result == {"id": 1, **updated}
    parking_from_db = db.session.query(Parking).where(Parking.id == 1).scalar()
    assert parking_from_db.to_json() == {"id": 1, **updated}


def test_update_parking_with_wrong_id():
    with pytest.raises(Missing):
        update_parking_json(
            parking_id=123,
            address="...",
            opened=False,
            count_places=123,
            count_available_places=456,
        )
